﻿using System.Linq;
using TrueSync;
using UnityEngine;

namespace HEFramework
{
    public static class TeamSystem
    {
        [EntitySystem]
        public class TeamAwakeSystem : AwakeSystem<Team>
        {
            protected override void Awake(Team _self)
            {
            }
        }


        [EntitySystem]
        public class TeamDestroySystem : DestroySystem<Team>
        {
            protected override void Destroy(Team _self)
            {
                for (int i = 0; i < _self.Heros.Count; i++)
                {
                    var entity = _self.Heros[i].Entity;
                    if (entity != null)
                    {
                        entity.Dispose();
                    }
                }
            }
        }

        public static Entity AddHero(this Team _self, int _id, TSVector _pos)
        {
            var camp = _self.GetSceneChild<Camp>();
            var factory = _self.GetSceneChild<Factory>();
            var element = _self.GetSceneChild<Element>();
            if (camp == null || factory == null || element == null)
            {
                return null;
            }

            if (_self.IsTeamMax())
            {
                return null;
            }

            var hero = factory.AddHero(_id, camp.MyID, _pos);
            element.UpdateHeroBuff(hero);
            _self.Heros.Add(hero);
            return hero;
        }

        public static Entity AddHeroRandomPos(this Team _self, int _id)
        {
            var factory = _self.GetSceneChild<Factory>();
            if (factory == null)
            {
                return null;
            }

            return _self.AddHero(_id, factory.GetRandomHeroGeneratePos());
        }

        public static Entity GetHero(this Team _self, int _heroID)
        {
            for (int i = 0; i < _self.Heros.Count; i++)
            {
                var hero = (Hero)_self.Heros[i].Entity;
                if (hero == null)
                {
                    continue;
                }

                if (hero.ID == _heroID)
                {
                    return hero;
                }
            }

            return null;
        }

        public static Entity GetHeroByIndex(this Team _self, int _index)
        {
            if (_index >= _self.Heros.Count)
            {
                return null;
            }

            return _self.Heros[_index].Entity;
        }

        public static bool IsTeamMax(this Team _self)
        {
            var dc = _self.GetSceneChild<DataTableComponent>();
            if (dc == null)
            {
                return false;
            }

            int max = dc.LoadDataTable<DRGlobalSettings>().GetData((int)eGlobalSetting.TeamPeople_MaxNum).Value1;
            return _self.Heros.Count >= max;
        }
    }
}